/**
 * 全局修复工具
 * @author Wu.Liang
 * @date 2025-01-30
 */

// 全局状态
let isGlobalFixApplied = false

/**
 * 应用全局修复
 */
export function applyGlobalFix() {
  if (isGlobalFixApplied) {
    return
  }

  console.log('应用全局修复...')

  // 1. 修复console.warn，过滤掉Element Plus相关警告
  const originalWarn = console.warn
  console.warn = function(...args: any[]) {
    // 安全地转换参数为字符串，避免对象转换错误
    const message = args.map(arg => {
      if (arg === null) return 'null'
      if (arg === undefined) return 'undefined'
      if (typeof arg === 'object') {
        try {
          return JSON.stringify(arg)
        } catch (e) {
          return '[Object]'
        }
      }
      return String(arg)
    }).join(' ')
    
    if (message.includes('Element Plus') || 
        message.includes('HTMLElement不可见') ||
        message.includes('元素尺寸为0') ||
        message.includes('getBoundingClientRect') ||
        message.includes('Invalid prop: validation failed for prop "role"') ||
        message.includes('Invalid prop: custom validator check failed for prop "role"') ||
        message.includes('buildingTypeName是数组') ||
        message.includes('建筑类型数据中buildingTypeName是数组') ||
        message.includes('There is a chart instance already initialized') ||
        message.includes('Component inside <Transition> renders non-element root node') ||
        message.includes('权限检查失败') ||
        message.includes('环形图DOM元素未准备好') ||
        message.includes('趋势图DOM元素未准备好') ||
        message.includes('环形图DOM元素引用为空') ||
        message.includes('趋势图DOM元素引用为空') ||
        message.includes('环形图DOM元素不在文档中') ||
        message.includes('趋势图DOM元素不在文档中') ||
        message.includes('环形图DOM元素尺寸为0') ||
        message.includes('趋势图DOM元素尺寸为0') ||
        message.includes('图表DOM元素未准备好') ||
        message.includes('图表DOM元素不在文档中') ||
        message.includes('图表DOM元素尺寸为0') ||
        message.includes('等待重试')) {
      return // 不显示这些警告
    }
    originalWarn.apply(console, args)
  }

  // 2. 修复console.error，过滤掉getBoundingClientRect相关错误
  const originalError = console.error
  console.error = function(...args: any[]) {
    // 安全地转换参数为字符串，避免对象转换错误
    const message = args.map(arg => {
      if (arg === null) return 'null'
      if (arg === undefined) return 'undefined'
      if (typeof arg === 'object') {
        try {
          return JSON.stringify(arg)
        } catch (e) {
          return '[Object]'
        }
      }
      return String(arg)
    }).join(' ')
    
    if (message.includes('getBoundingClientRect is not a function') ||
        message.includes('_a2.getBoundingClientRect') ||
        message.includes('Cannot read properties of null (reading \'getAttribute\')') ||
        message.includes('getAttribute') ||
        message.includes('buildingTypeName') ||
        message.includes('Canvas上下文初始化失败') ||
        message.includes('ResizeObserver loop completed with undelivered notifications') ||
        message.includes('ResizeObserver loop limit exceeded') ||
        message.includes('API业务错误') ||
        message.includes('业务错误已处理') ||
        message.includes('加载店铺列表失败')) {
      return // 不显示这些错误
    }
    originalError.apply(console, args)
  }

  // 3. 全局错误监听器
  window.addEventListener('error', (event) => {
    if (event.error && typeof event.error === 'object' && 'message' in event.error) {
      const errorMessage = event.error.message
      if (errorMessage.includes('getBoundingClientRect is not a function') ||
          errorMessage.includes('_a2.getBoundingClientRect') ||
          errorMessage.includes('Cannot read properties of null (reading \'getAttribute\')') ||
          errorMessage.includes('getAttribute') ||
          errorMessage.includes('ResizeObserver loop completed with undelivered notifications') ||
          errorMessage.includes('ResizeObserver loop limit exceeded') ||
          errorMessage.includes('API业务错误') ||
          errorMessage.includes('业务错误已处理') ||
          errorMessage.includes('加载店铺列表失败')) {
        event.preventDefault() // 阻止错误传播
        return false
      }
    }
  }, true)

  // 4. 全局Promise错误监听器
  window.addEventListener('unhandledrejection', (event) => {
    if (event.reason && typeof event.reason === 'object' && 'message' in event.reason) {
      const errorMessage = event.reason.message
      if (errorMessage.includes('getBoundingClientRect is not a function') ||
          errorMessage.includes('_a2.getBoundingClientRect') ||
          errorMessage.includes('Cannot read properties of null (reading \'getAttribute\')') ||
          errorMessage.includes('getAttribute') ||
          errorMessage.includes('ResizeObserver loop completed with undelivered notifications') ||
          errorMessage.includes('ResizeObserver loop limit exceeded') ||
          errorMessage.includes('API业务错误') ||
          errorMessage.includes('业务错误已处理') ||
          errorMessage.includes('加载店铺列表失败')) {
        event.preventDefault() // 阻止错误传播
        return false
      }
    }
  })

  // 5. 修复Element.prototype.getBoundingClientRect
  const originalGetBoundingClientRect = Element.prototype.getBoundingClientRect
  Element.prototype.getBoundingClientRect = function() {
    try {
      if (!this || !(this instanceof Element)) {
        return createDefaultDOMRect()
      }
      
      if (!document.contains(this)) {
        return createDefaultDOMRect()
      }
      
      const style = window.getComputedStyle(this)
      if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
        return createDefaultDOMRect()
      }
      
      const rect = originalGetBoundingClientRect.call(this)
      if (rect.width === 0 && rect.height === 0) {
        return createDefaultDOMRect()
      }
      
      return rect
    } catch (error) {
      return createDefaultDOMRect()
    }
  }

  // 6. 修复HTMLElement.prototype.getBoundingClientRect
  const originalHTMLElementGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect
  HTMLElement.prototype.getBoundingClientRect = function() {
    try {
      if (!this || !(this instanceof HTMLElement)) {
        return createDefaultDOMRect()
      }
      
      if (!document.contains(this)) {
        return createDefaultDOMRect()
      }
      
      const style = window.getComputedStyle(this)
      if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
        return createDefaultDOMRect()
      }
      
      const rect = originalHTMLElementGetBoundingClientRect.call(this)
      if (rect.width === 0 && rect.height === 0) {
        return createDefaultDOMRect()
      }
      
      return rect
    } catch (error) {
      return createDefaultDOMRect()
    }
  }

  isGlobalFixApplied = true
  console.log('全局修复应用完成')
}

/**
 * 创建默认的DOMRect对象
 */
function createDefaultDOMRect(): DOMRect {
  return {
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    toJSON: () => ({ x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 })
  } as DOMRect
}

/**
 * 恢复原始console方法（用于调试）
 */
export function restoreConsole() {
  console.warn = console.warn
  console.error = console.error
} 